<?php  
namespace app\common\services\weixin;

use \app\common\services\BaseService;
use \app\models\Member\OauthAccessToken;
use \app\common\components\HttpClient;
use \app\common\components\HttpCurl;
/**
* 
*/
class RequestServices extends BaseService
{
	
	private static $app_token="";
	private static $appid="";
	private static $app_secret="";

	private static $url='https://api.weixin.qq.com/cgi-bin/';
	//获取access_token
	public static function getAccessToken(){

		$data_now=time();
		$access_token_info=OauthAccessToken::find()->where(['>','expired_time',$data_now])->limit(1)->one();
		if($access_token_info){
			return $access_token_info['access_token'];
		}
		self::setConfig(\Yii::$app->params['weixin']['appid'],self::$app_token,\Yii::$app->params['weixin']['sk']);
		//调用接口
		$path='token?grant_type=client_credential&appid='.self::getAppId().'&secret='.self::getAppSecret().'';
		// return $path;
		
		$res=self::send($path);
		$new_access_token=new OauthAccessToken();
		$new_access_token->access_token=$res['access_token'];
		$new_access_token->created_time=time();
		$new_access_token->expired_time=time()+200;
		$new_access_token->save(0);
		return $res['access_token'];
	}
	//封装发送请求接口
	public static function send($path,$data=[],$method="GET"){
		$request_url=self::$url.$path;
		// echo $request_url; 
		// exit;
		if($method=="POST"){
			// var_dump($data);
			$res=HttpCurl::post($request_url,$data);
			// var_dump($res);
		}else{
			$res=HttpCurl::get($request_url);
		}

		$ret=@json_decode($res,true);
		// var_dump($ret);
		if(!$ret || (isset($ret['errcode'])) && $ret['errcode']){
			// echo '123';
			return self::_err($ret['errmsg']);
		}
		return $ret;
	}
	public static function setConfig($appid,$app_token,$app_secret){
		self::$appid=$appid;
		self::$app_token=$app_token;
		self::$app_secret=$app_secret;
	}

	public static function getAppToken(){
		return self::$app_token;
	}
	public static function getAppId(){
		return self::$appid;
	}
	public static function getAppSecret(){
		return self::$app_secret;
	}
}
?>